//
//  XCNSDictionary.m
//  IOSDome
//
//  Created by 刘波 on 2019/5/9.
//  Copyright © 2019 clobe. All rights reserved.
//

#import "XCNSDictionary.h"

@implementation XCNSDictionary


/**
 字典的基本用法
 */
-(void)setNSDictionary{
    NSDictionary *dic;
    //创建一个空字典
    dic = [[NSDictionary alloc] init];
    dic = [NSDictionary dictionary];
    dic = [NSDictionary new];
    //通过指定对象创建字典
    dic = [NSDictionary dictionaryWithObject:@"value" forKey:@"key"];
    dic = [[NSDictionary alloc] initWithObjectsAndKeys:@"value",@"key", nil];
    dic = [NSDictionary dictionaryWithObjects:@[@"value1",@"value2"] forKeys:@[@"key1",@"kae2"]];
    //通过字典创建字典
    NSDictionary *dic1 = [NSDictionary dictionaryWithDictionary:dic];
    //获取字典中元素的个数
    NSInteger num = [dic count];
    //通过key获取元素
    NSString *value = [dic objectForKey:@"key"];
    //字典所有键
    NSArray *keys = [dic allKeys];
    //字典所有值
    NSArray *values = [dic allValues];
    //返回一个值对应的所有键
    NSArray *arr;
    arr = [dic allKeysForObject:@"value1"];
    //如果找不到对应的值，返回nil
    arr = [dic objectsForKeys:@[@"value1",@"value2"] notFoundMarker:@"nil"];
    //字典转json
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:0];
    NSString *dataStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"字典转json:%@",dataStr);
    
    //可变字典
    NSMutableDictionary *mDic;
    //初始化一个指定大小的可变字典
    mDic = [NSMutableDictionary dictionaryWithCapacity:10];
    mDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    //新增元素 如果key已经存在，则替换value值
    [mDic setObject:@"value2" forKey:@"key2"];
    [mDic setValue:nil forKey:@"key3"]; //setValue 的value值可以为nil而不报错
    //删除指定对象值
    [mDic removeObjectForKey:@"key2"];
    //删除所有对象
    [mDic removeAllObjects];
}

@end
